package 结构性模式


/**
 * 运用共享技术有效地支持大量细粒度的对象
 */
class Student(id: Int, name: String) {
    companion object {
        private val cache = HashMap<String, Student>()

        fun create(id: Int, name: String): Student {
            val key = "$id-$name"
            var std = cache[key]
            if (std == null) {
                std = Student(id, name)
                cache[key] = std
            }
            return std
        }
    }
}

/**
 * 单例不是不变，是不允许创建新实例
 * 享元要求实例不变，所以才能把"应该创建一个新实例"的操作给优化成"直接返回一个缓存的实例"
 */

// 享元接口
interface Shape {
    fun draw(color: String)
}

// 具体享元类
class Circle : Shape {
    private var x: Int = 0
    private var y: Int = 0

    override fun draw(color: String) {
        println("Drawing a $color circle at ($x, $y)")
    }

    fun setPosition(x: Int, y: Int) {
        this.x = x
        this.y = y
    }
}

// 享元工厂类
class ShapeFactory {
    private val circleMap: MutableMap<String, Circle> = hashMapOf()

    fun getCircle(color: String): Circle {
        var circle = circleMap[color]

        if (circle == null) {
            circle = Circle()
            circleMap[color] = circle
        }

        return circle
    }
}

// 客户端代码
fun main() {
    val shapeFactory = ShapeFactory()

    val circle1 = shapeFactory.getCircle("Red")
    circle1.setPosition(10, 20)
    circle1.draw("Red")

    val circle2 = shapeFactory.getCircle("Blue")
    circle2.setPosition(30, 40)
    circle2.draw("Blue")

    val circle3 = shapeFactory.getCircle("Red")
    circle3.setPosition(50, 60)
    circle3.draw("Red")
}